/***********************************
* 上机作业1
* 编写程序实现约瑟夫（Josephu）问题，
* n、m、k为外部输入，并打印输出结果。
************************************/ 

#include<stdio.h>
#include<malloc.h>

struct NODE;
typedef struct NODE node;
struct NODE{int data;node* next;};

void Josephu(node* h,int n,int m,int k){
    int i = 0;
    node* p = h->next;
    node* q;
    int cnt = k-1+n;
    while(--cnt)p=p->next;
    for(i=0;i<n;i++){
        while(++cnt<m)p=p->next;
        q = p->next;
        printf("Round %4d: %4d.\n",i+1,q->data);
        p->next = q->next;
        free(q);
        cnt = 0;
    }
}

int main(){
    node head;
    node* h = &head;
    node* p = h;
    int n = 0,m=0,k=0,i = 0;
    printf("Enter m n k: ");
    if(scanf("%d%d%d",&m,&n,&k)!=3&&m>0&&n>0&&k>0){printf("invalid m,n,k.\n");return 0;}
    for(i=0;i<n;i++){
        p->next = malloc(sizeof(node)); 
        p=p->next;
        p->data = i+1;
    }
    p->next=h->next;

    Josephu(h,n,m,k);
    return 0;
}